package com.zhkj.txg.widget

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.abs

class ViewPager2RecyclerView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : RecyclerView(context, attrs, defStyle) {
    private var startX = 0
    private var startY = 0

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        ev?.let {
            when (ev.action) {
                MotionEvent.ACTION_DOWN -> {
                    startX = ev.x.toInt()
                    startY = ev.y.toInt()
                    parent.requestDisallowInterceptTouchEvent(true)
                }
                MotionEvent.ACTION_MOVE -> {
                    val disX = abs(ev.x - startX)
                    val disY = abs(ev.y - startY)
                    if (disX > disY) {
                        parent.requestDisallowInterceptTouchEvent(canScrollHorizontally((startX - ev.x).toInt()))
                    } else parent.requestDisallowInterceptTouchEvent(canScrollVertically((startY - ev.y).toInt()))
                }
                MotionEvent.ACTION_UP or MotionEvent.ACTION_CANCEL -> {
                    parent.requestDisallowInterceptTouchEvent(false)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }
}